const std = @import("std");
const cz = @import("cz-runtime");

// 聊天消息
const ChatMsg = union(enum) {
    join: []const u8,
    message: []const u8,
    leave,
    stop,
};

// 聊天室状态
const ChatRoomState = struct {
    users: std.ArrayList([]const u8),
    message_count: u32,
};

const ChatRoomActor = cz.Actor(ChatRoomState, ChatMsg);

fn chatRoomHandler(actor: *ChatRoomActor, msg: ChatMsg) !void {
    switch (msg) {
        .join => |username| {
            // 使用 Actor 的独立分配器
            const name_copy = try actor.allocator.dupe(u8, username);
            try actor.state.users.append(actor.allocator, name_copy);
            std.debug.print("[ChatRoom] {s} joined. Total users: {d}\n", 
                .{username, actor.state.users.items.len});
        },
        .message => |text| {
            actor.state.message_count += 1;
            std.debug.print("[ChatRoom] Message #{d}: {s}\n", 
                .{actor.state.message_count, text});
        },
        .leave => {
            if (actor.state.users.items.len > 0) {
                const user = actor.state.users.pop();
                std.debug.print("[ChatRoom] User left\n", .{});
                _ = user;
            }
        },
        .stop => {
            actor.stop();
        },
    }
}

pub fn main() !void {
    std.debug.print("=== Cz Language - Chat Room Example ===\n\n", .{});
    
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    
    const alloc = gpa.allocator();
    
    var system = cz.ActorSystem.init(alloc);
    
    // 创建聊天室 Actor
    const initial_state = ChatRoomState{
        .users = std.ArrayList([]const u8).initCapacity(alloc, 10) catch std.ArrayList([]const u8){},
        .message_count = 0,
    };
    
    var chat_room = try system.spawn(ChatRoomState, ChatMsg, initial_state);
    defer {
        chat_room.state.users.deinit(alloc);
        chat_room.deinit(alloc);
    }
    
    try chat_room.start(&chatRoomHandler);
    
    // 模拟用户加入和发消息
    try chat_room.send(.{ .join = "Alice" });
    std.Thread.sleep(50_000_000);
    
    try chat_room.send(.{ .join = "Bob" });
    std.Thread.sleep(50_000_000);
    
    try chat_room.send(.{ .message = "Hello everyone!" });
    std.Thread.sleep(50_000_000);
    
    try chat_room.send(.{ .message = "How are you?" });
    std.Thread.sleep(50_000_000);
    
    try chat_room.send(.leave);
    std.Thread.sleep(50_000_000);
    
    try chat_room.send(.stop);
    std.Thread.sleep(50_000_000);
    
    std.debug.print("\n=== Example completed ===\n", .{});
}
